package com.wyg.cookie;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CookiesServlet
 */
@WebServlet("/CookiesServlet")
public class CookiesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookiesServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		String userName = null;
		String userPassword = null;
		Cookie[] cookies = request.getCookies();
		if(cookies==null){
			userName = request.getParameter("name");
			userPassword = request.getParameter("password");
			if(userName!=null){
				Cookie nameCookie = new Cookie("userName", userName);
				Cookie passwordCookie = new Cookie("userPassword",userPassword);
				
				nameCookie.setMaxAge(30*60);
				passwordCookie.setMaxAge(30*60);
				
				response.addCookie(nameCookie);
				response.addCookie(passwordCookie);
				
				request.getSession().setAttribute("userName",userName);
				request.getRequestDispatcher("NewFile.jsp").forward(request, response);
			}else{
				response.sendRedirect("login.jsp");
			}
			
		}else{
			for(Cookie cookie:cookies){
				if("userName".equals(cookie.getName())){
					userName = cookie.getValue();
				}
				if("userPassword".equals(cookie.getName())){
					userPassword = cookie.getValue();
				}
			}
			request.getSession().setAttribute("userName",userName);
			request.getRequestDispatcher("NewFile.jsp").forward(request, response);
		}
		

		
		
	}

}
